import React, { useState, useEffect, useRef, MouseEvent } from "react";
import MermaidChart from "./mermaid-diagram";
import { CustomizationDropdown } from "./customization-dropdown";
import { ZoomControl } from "./zoom-control";
import { useRouter, usePathname } from "next/navigation";

interface DiagramViewProps {
  diagram: string;
  lastGenerated: Date;
  onModify: (instructions: string) => void;
  onRegenerate: (instructions: string) => void;
  zoomingEnabled: boolean;
  repoUrl?: string;
}

export function DiagramView({
  diagram,
  lastGenerated,
  onModify,
  onRegenerate,
  zoomingEnabled,
  repoUrl,
}: DiagramViewProps) {
  const [zoom, setZoom] = useState(100);
  const containerRef = useRef<HTMLDivElement>(null);
  const wrapperRef = useRef<HTMLDivElement>(null);
  const [isDragging, setIsDragging] = useState(false);
  const [dragPosition, setDragPosition] = useState({ x: 0, y: 0 });
  const [startPosition, setStartPosition] = useState({ x: 0, y: 0 });

  const handleZoomChange = (newZoom: number) => {
    setZoom(newZoom);
    
    if (containerRef.current) {
      // 我们可以通过缩放容器来控制图表大小
      const scale = newZoom / 100;
      containerRef.current.style.transform = `scale(${scale})`;
      containerRef.current.style.transformOrigin = 'top center';

      // 重置拖动位置，避免缩放时位置异常
      setDragPosition({ x: 0, y: 0 });
      if (wrapperRef.current) {
        wrapperRef.current.style.transform = `translate(0px, 0px)`;
      }
    }
  };

  // 开始拖动
  const handleMouseDown = (e: MouseEvent<HTMLDivElement>) => {
    // 移除缩放限制，允许任何比例都可以拖动
    setIsDragging(true);
    setStartPosition({ x: e.clientX, y: e.clientY });
  };

  // 拖动过程
  const handleMouseMove = (e: MouseEvent<HTMLDivElement>) => {
    if (!isDragging) return;
    
    const deltaX = e.clientX - startPosition.x;
    const deltaY = e.clientY - startPosition.y;
    
    const newPosition = {
      x: dragPosition.x + deltaX,
      y: dragPosition.y + deltaY
    };
    
    if (wrapperRef.current) {
      wrapperRef.current.style.transform = `translate(${newPosition.x}px, ${newPosition.y}px)`;
    }
    
    setStartPosition({ x: e.clientX, y: e.clientY });
    setDragPosition(newPosition);
  };

  // 结束拖动
  const handleMouseUp = () => {
    setIsDragging(false);
  };

  // 添加鼠标离开事件处理
  const handleMouseLeave = () => {
    setIsDragging(false);
  };

  // 在组件卸载时移除事件监听器
  useEffect(() => {
    return () => {
      setIsDragging(false);
    };
  }, []);

  return (
    <div className="flex w-full flex-col gap-8">
      <div className="w-full">
        <CustomizationDropdown
          onModify={onModify}
          onRegenerate={onRegenerate}
          lastGenerated={lastGenerated}
          isOpen={true}
        />
      </div>
      
      {/* 添加缩放控制器 */}
      <div className="flex justify-end mb-2">
        <ZoomControl onZoomChange={handleZoomChange} initialZoom={100} />
      </div>
      
      <div 
        className="flex w-full justify-center overflow-hidden"
        style={{ 
          cursor: isDragging ? 'grabbing' : 'grab',
          position: 'relative',
          minHeight: '500px'
        }}
        onMouseDown={handleMouseDown}
        onMouseMove={handleMouseMove}
        onMouseUp={handleMouseUp}
        onMouseLeave={handleMouseLeave}
      >
        <div 
          ref={wrapperRef} 
          className="transition-transform w-full"
          style={{ 
            transform: `translate(${dragPosition.x}px, ${dragPosition.y}px)`,
            position: 'absolute',
            top: 0,
            left: 0,
            right: 0
          }}
        >
          <div 
            ref={containerRef} 
            className="w-full transition-transform duration-300"
            style={{ 
              transformOrigin: 'top center' 
            }}
          >
            <MermaidChart chart={diagram} zoomingEnabled={zoomingEnabled} repoUrl={repoUrl} />
          </div>
        </div>
      </div>
    </div>
  );
}